package com.lwl.blue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lwl.blue.commont.base.BaseController;
import com.lwl.blue.commont.base.JsonResult;
import com.lwl.blue.commont.base.LoginUser;
import com.lwl.blue.commont.enums.FileUploadTypeEnum;
import com.lwl.blue.commont.enums.PowerDataTypeEnum;
import com.lwl.blue.commont.enums.SourceTypeEnum;
import com.lwl.blue.commont.utils.FileUtils;
import com.lwl.blue.commont.utils.MD5Utils;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.Files;
import com.lwl.blue.entity.Users;
import com.lwl.blue.service.FilesService;
import com.lwl.blue.service.ItemService;
import com.lwl.blue.service.UsersService;
import com.lwl.blue.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.Date;
import java.util.Objects;

import static com.lwl.blue.commont.base.Const.LONGIN_ATTR;

/**
 * <p> 首页 </p>
 *
 * @Date: 2021/11/2 11:23
 * @version: V1.0
 * @Decription:
 * @author: 蓝文良
 */
@Controller
@Slf4j
public class IndexController extends BaseController {
    @Value("${upload.filePath}")
    private String filePath;
    @Value("${upload.file.maxSize}")
    private String fileMaxSize;
    @Value("${export.file.path.prefix}")
    private String prefix;
    @Value("${session.timeout}")
    private Integer sessionTimeout;

    @Resource
    UsersService usersService;
    @Resource
    ItemService itemService;
    @Resource
    FilesService filesService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String homePage(HttpServletRequest request, HttpServletResponse response) {
        return "index.html";
    }

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, HttpServletResponse response) {
        return "index.html";
    }

    @RequestMapping(value = "loginPage", method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response) {
        Object loginUser = request.getSession().getAttribute(LONGIN_ATTR);
        if (null != loginUser) {
            request.getSession().removeAttribute(LONGIN_ATTR);
        }
        return "common/login.html";
    }

    @CrossOrigin
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult login(@RequestBody @Valid LoginUser loginUser, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(loginUser.getUsername())
                || StringUtils.isBlank(loginUser.getPassword())) {
            return new JsonResult().error("账号或密码不能为空");
        }

        Users user = usersService.getOne(new QueryWrapper<Users>().lambda()
                .eq(Users::getUserName, loginUser.getUsername())
                .eq(Users::getIsDelete, 0));
        if (user == null) {
            System.out.println("用户不存在！！");
            return new JsonResult().error("用户不存在");
        }
        String pwd;
        try {
            pwd = MD5Utils.EncoderByMd5(loginUser.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().error("密码解析错误错误");
        }
        if (!user.getPassword().equals(pwd)) {
            return new JsonResult().error("密码错误");
        }
        LoginUserInfo loginUserInfo = new LoginUserInfo();
        BeanUtils.copyProperties(user, loginUserInfo);
        if (Objects.nonNull(user.getPowerLastTime())
                && PowerDataTypeEnum.NOT_SELECT.getValue() != user.getPowerDataType()) {
            Date now = new Date();
            if (0 < now.compareTo(user.getPowerLastTime())) {
                usersService.update(new UpdateWrapper<Users>().lambda()
                        .set(Users::getPowerLastTime, null)
                        .set(Users::getPowerDataType, PowerDataTypeEnum.NOT_SELECT.getValue())
                        .eq(Users::getId, user.getId()));
                loginUserInfo.setPowerDataType(PowerDataTypeEnum.NOT_SELECT.getValue());
            }
        }
        //session方式
        HttpSession session = request.getSession();
        session.setAttribute(LONGIN_ATTR, loginUser.getUsername());    //session中存的值
        UserContextUtil.setUser(loginUserInfo, session);
        session.setMaxInactiveInterval(sessionTimeout);
        return new JsonResult().success(user);
    }

    @RequestMapping(value = "/uploadFile/{type}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult upload(@RequestParam("file") MultipartFile uploadFile, @PathVariable(value = "type") String type) throws UnsupportedEncodingException {

        return uploadFile(uploadFile,type,null);
    }

    @RequestMapping(value = "/uploadFile/{type}/{sourceId}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult uploadTow(@RequestParam("file") MultipartFile uploadFile, @PathVariable(value = "type") String type, @PathVariable(value = "sourceId") String sourceId) throws UnsupportedEncodingException {
        return uploadFile(uploadFile,type,sourceId);
    }

    /**
     * 文件上传
     * @param uploadFile
     * @param type
     * @param sourceId
     * @return
     * @throws UnsupportedEncodingException
     */
    private JsonResult uploadFile(MultipartFile uploadFile, String type, String sourceId) throws UnsupportedEncodingException {
        InputStream inputStream = null;
        String reMessage = "上传成功";
        String fileName = "";
        if (type.equals(FileUploadTypeEnum.ITEM_QUICK.getType())) {
            fileName = uploadFile.getOriginalFilename();
            type = SourceTypeEnum.ITEM.getValue();
        } else {
            fileName = System.currentTimeMillis() + uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf("."));

        }
        //去除空格和对字符串编码
        fileName = fileName.replaceAll("\\s*", "");
        String secondHalf;
        try {
            secondHalf = type + "/" + LocalDate.now().getYear() + "/" + fileName;
            String file = filePath + secondHalf;
            inputStream = uploadFile.getInputStream();
            //文件大小校验
            if (!com.lwl.blue.commont.utils.FileUtils.checkFileSize(Integer.valueOf(inputStream.available()).longValue(), 50, "M")) {
                return new JsonResult().error("上传文件已超过上传最大值：" + fileMaxSize + " M");
            }
            //判断文件是否存在
            File upFile = new File(file);
            //文件存在
            if (upFile.exists()) {
                reMessage = "文件已存在，替换成功";
            }
            //保存文件
            FileUtils.upload(file, uploadFile);
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
        String filePath = prefix + secondHalf;
        if (FileUploadTypeEnum.ITEM_QUICK.getType().equals(type)) {
            itemService.updatePhoneByFileUpload(fileName, filePath);
        }
        Files files = new Files();
        files.setFileSize(uploadFile.getSize());
        files.setTypeName(SourceTypeEnum.getName(type));
        files.setFileName(fileName);
        files.setSourceName(uploadFile.getOriginalFilename());
        files.setSourceId(null==sourceId?null:Integer.valueOf(sourceId));
        files.setFilePath(secondHalf);
        files.setUrl(filePath);
        files.setSourceIsDelete(0);
        files.setWeight(0);
        setInsetOrUpdateUser(files);
        filesService.save(files);
        //转换成可以直接访问的地址
        JsonResult re = new JsonResult().success(reMessage);
        re.setData(filePath);
        return re;
    }

}
